<template><!---->
	<search-table
			:columns="userColumns" 
			:data="projectGroupMemberList"
            :total="groupMemberTotal"
            :page.sync="queryGroupMemberInfo.pageIndex"
            :size.sync="queryGroupMemberInfo.pageSize"
            @change-size="changeSize"
            @change-page="changePage"
        >
		<Alert type="warning" show-icon v-if="![0,7,10].includes(this.type) && step!= 'mid' && configMode !== 1" slot="alert">
			<p style="color:#f90">自动分配需要满足的条件：</p>
			<p>1、环境部署成功  </p>
			<p>2、{{type === 10 ? '角色':'团队'}}配置完成 </p>
			<p>3、{{type === 10 ? '角色':'团队'}}人员分配完成</p>
			<p v-if="type !== 10">4、分配原则：按照{{type === 10 ? '角色':'团队'}}的势力方分配环境</p>
		</Alert>
		<template slot="search">
			<Button  type='primary' ghost @click="dealAutoAllotData"
					 :disabled="disabledAllBtn || disabledAutoAllot || disabledAutoAllot1"
					 icon="ios-options"
					  style="margin-right:15px;"
					  v-if="(![0,7,10].includes(this.type) && step!= 'mid') && configMode !== 1">一键接入机器</Button>
    		<Select filterable v-model="queryGroupMemberInfo.accessGroupId" style="width:150px;margin-right:15px;"
					@on-change="changePage(1)" transfer clearable :placeholder="`请选择${type === 10 ? '角色':'团队'}`">
    		    <Option v-for="item in teamOptions" :value="item.id" :key="item.id" :title="item.name">{{ item.name }}</Option>
    		</Select>
			<span style="color:red">{{autoConfigTip}}</span>
		</template>
	    <Modal v-model="accessVmModal.show"
        	:title="accessVmModal.title"
        	:width="720"
        	ok-text="接入"
        	@on-cancel="getAccessGroupList"
        	:mask-closable = "false"
        	footer-hide>
        	<Row>
				接入用户  <Tag color="blue">{{selectUser.userName}}</Tag>
				<!--<span v-show="type != 5 && type != 0">
					子网络 <Select filterable v-model="networkId" style="width:200px" :transfer="true" @on-change="getOptionalVms" label-in-value :disabled="selectVms.length > 0" filterable>
			        <Option value="all">所有</Option>
			        <Option v-for="item in subnetList" :value="item.id" :key="item.id">{{ item.name || item.district }}</Option>
			    </Select>-->
				<Checkbox v-model="record" style="float:right" @on-change="deviceToUser('tagRemove')">是否录屏</Checkbox>
				<Checkbox v-model="access" style="float:right" @on-change="deviceToUser('tagRemove')">允许接入</Checkbox>

			</Row>
			<Row style="margin-top:10px;">已配置机器 <Tag type="border" closable color="primary" v-for="device in selectUser.deviceList" :key="device.deviceId" @on-close="removeDevice" :name="device.deviceId">{{device.deviceName}}</Tag>
			<Button type="error" @click="clearDevices" size="small">清空机器</Button></Row>
			<Transfer
		        :titles='["可选虚拟机","已选虚拟机"]'
		        :operations="['移除','选择']"
		        :list-style="listStyle"
		        :render-format="render1"
		        :data="optionalVms"
		        :target-keys="selectVms"
		        filterable
		        :filter-method="filterMethod"
		        @on-change="handleChangeVm"
		        @on-selected-change="handleChangeSelectVm"
		        style="margin:10px 0"
		        v-if="accessVmModal.show">
	       </Transfer>
	    </Modal>
	</search-table>
</template>

<script>
	import {getDrillSecensList} from '@/api/drill'
//  import encryption from '@/libs/encryption.js'
	import {getaccessgrouplist,getuserinstance,setuservmrelation,getUserInstanceExclude,getpartylist} from '@/api/access_new'
	import {queryVmWithParty, queryNetworkList, getTargetTeamList_new, autoAllotTopoTarget,
		queryCtfTarget, ctfTargetAllot,autoConfigAccessVm} from '@/api/drill_compete'
	import {getstatusbyprjid,hostDetail} from '@/api/drill'
	export default {
	    name: 'scenes',
	    components:{},
	    props:['type','disabledAllBtn','step', 'configMode','isDistributed','hlConfig','hwType'],
		data(){
//		let September = sessionStorage.getItem('November')
//      September = JSON.parse(encryption.SelfUseDecrypt(September))
	  	return {
//	  		USER_ID:September.userId,
//          USER_Name:September.nickname,
			rangeId:'',
	  		projectId:this.$route.query.prjid,
        	testId:this.$route.query.id,
//     		optionalVms:[],
       		allOptionalVms:[],
       		selectVms:[],
       		record:true,
       		access:true,
       		selectUser:{}, // 当前用户
       		selectUserList:[],
       		listStyle: {
                width: '290px',
                height: '300px'
           },
		  	project:{
	            drillitemname:this.$route.query.name,
	            projectid:this.$route.query.prjid,
	            drillitemid:this.$route.query.id,
	            testId:this.$route.query.id
	        },
			accessGroupList:[],
			teamOptions: [],
			accessVmModal:{
				show:false,
				loading:true,
				title:'接入机器'
			},
			queryGroupMemberInfo:{
				testId:this.$route.query.id,
				pageIndex:1,
				pageSize:10
			},
			groupMemberTotal:0,
            projectGroupMemberList:[],
            projectInfo:{},
            subnetList:[],
            network:{},
            networkId:'all',
            userColumns:[
//         		{
//                  type: 'selection',
//                  width: 60,
//                  align: 'center'
//              },
				{
					title:'昵称',
					key:'userName',
					align: 'center',
					placement:'top-left',
					tooltip:true,
					width: 300
				},
				{
					title:`${this.type === 10 ? '角色':'团队'}`,
					key:'accessGroupName',
					align: 'center',
					width:100,
					tooltip:true
//					filters:[],
//                  filterMethod (value, row) {
//                      return row.accessGroupName.indexOf(value) > -1;
//                  }
				},
//				{
//					title:'fromType',
//					key:'fromType'
//				},
//				{
//					title:'接入/移除机器',
//					type:"expand",
//					align: 'center',
//					render:(h,params) => {
//						return h(AccessVmTransfer,{
//							props:{
//								selectUser:params.row,
//								project:this.project,
//								type:'vm',
//								show:true
//							}
//						})
//					}
//				},
				{
					title:'创建时间',
					key:'created',
					align: 'center'
				},
				{
					title:'已分配网络',
					key:'networkName',
					align: 'center',
					width:100,
					tooltip:true
				},
				{
					title:'势力方',
					key:'party',
					align: 'center',
					minWidth:60,
					tooltip:true,
					filter:(party,data) => {
						return party ? party.name : ''
					},
					setColor:(party,data) => {
						return party ? party.partyColor : ''
					},
					// render:(h,params) => {
					// 	if(!params.row.party){
					// 		return
					// 	}
					// 	return h('Tooltip',{
					// 		'class':'tableTooltip',
					// 		props:{
					// 			maxWidth:400,
					// 			placement:'top',
					// 			triggle:'hover',
					// 			transfer:true
					// 		},
					// 		style:{
					// 			color:params.row.party.partyColor
					// 		}
					// 	},[
					// 		h('p',{
					// 			'class':'showContent',
					// 			style:{
					// 				maxWidth:'60px'
					// 			}
					// 		},params.row.party.name),
					// 		h('div',{
					// 			'class':'tooltipContent',
					// 			slot:'content'
					// 		},params.row.party.name)
					// 	])
					// }
	    		},
				{
		            title: '已配置机器',
		            key: 'useerList',
		            align: 'center',
					minWidth:300,
		            render:(h,params) => {
		            	let arr = [];
		            	if(params.row.deviceList.length > 0){
		            		arr = params.row.deviceList.map(device => {
			            		return h('Tag',{
			            			props:{
			            				type:"border",
			//          				closable:true,
			            				color:"primary"
			            			}
			            		},[
				            		h('img',{
			            				attrs:{
			            					src:require("../../../assets/scene/vm.png")
			            				},
			            				style: {
	//			                            cursor: 'pointer',
	//			                            'margin-right':'5px',
				                            'vertical-align': 'middle',
	//			                            width:'16px',
	//			                            height:'16px',
	//			                            display:'inline-block',
	//			                            marginBottom:'4px',
				                        },
			            			}),
			            			h('span',{
			            				style:{
			            					display:'inline-block',
			            					width:0,
			            					height:'100%',
			            					margin:'0 8px',
			            					borderLeft:'1px dashed #2d8cf0',
			            					verticalAlign:'middle'
			            				}
			            			}),
			            			h('span',device.deviceName)
			            		])
			            	})
		            	}
		            	return h('div',{class:'flex-wrap'},arr.length > 0 ? arr : '无');
		            }
		        },
				{
					title: '操作',
					width: 120,
					placement:'top-right',
					key:'action',
					show:(data) => {
						return this.configMode === 1 ? false : true
					},
					opList: [
                        {
							type:'access',
                            txt: '接入/移除',
                            disabled: (data) => {
                                return this.disabledAllBtn;
                            },
							show:(data) => {
								return this.configMode === 1 ? false : true
							},
                            fun: (data) => {
                                this.selectUser = data;
								this.allOptionalVms = [];
                                this.accessVmModal.show = true;
                                this.networkId = '';
                                this.selectVms = data.deviceList.map((vm) => vm.deviceId);
								this.rangeId=data.rangeId
                                this.record = data.deviceList.every(
                                    (item) => item.enableRecordScreen
                                );
                                this.access = data.deviceList.every((item) => item.enabled);
                                this.getProjectSubnet();
                                //										this.getOptionalVms(); //根据势力方筛选机器
                            }
                        }
                    ],
           	    	// render:(h,params) => {
           	    	// 	return h('div', [
           	    	// 		h('Button', {
					// 			props: {
					// 				type: 'text',
					// 				size: 'small',
					// 				disabled:this.disabledAllBtn
					// 			},
					// 			attrs:{
					// 				title:'接入/移除'
					// 			},
					// 			style: {
					// 				border:'none',
					// 				background:'none',
					// 				boxShadow:'none',
					// 				display:this.configMode === 1 ? 'none':'inline-block'
					// 			},
					// 			on: {
					// 				click: () => {
					// 					this.selectUser = params.row;
					// 					this.allOptionalVms = [];
					// 					this.accessVmModal.show = true;
					// 					this.networkId = '';
					// 					this.selectVms = params.row.deviceList.map(vm => vm.deviceId);
					// 					this.rangeId=params.row.rangeId
					// 					this.record = params.row.deviceList.every(item => item.enableRecordScreen)
					// 					this.access = params.row.deviceList.every(item => item.enabled)
					// 					this.getProjectSubnet();
					// 				}
					// 			}
					// 		}, [
					// 			h('img', {
			        //                 attrs: {
			        //                 	src:this.disabledAllBtn ? require('../../../assets/scene/dis-access.png') : require('../../../assets/scene/access.png')
			        //                 },
			        //                 style: {
			        //                     cursor: 'pointer',
			        //                     'vertical-align': 'middle',
			        //                     display:'inline-block',
			        //                     marginBottom:'4px',
			        //                 },
			        //             }),
			        //             h('span',{
			        //                 style: {
			        //                     cursor: 'pointer',
					// 					color:'#2d8cf0'
			        //                 },
			        //             })
					// 		])
           	    	// 	])
           	    	// }
           	    }

            ],
            curSelectVms:[],
            allProjectGroupMember:[],
            disabledAutoAllot1:false,
            allVms:[],
            partyList:[],
            autoConfigTip:''
	  	}
	},
	filters:{

	},
	computed:{
		optionalVms:function(){
			let _this = this;
			if(this.type == 0 || this.type == 5 || this.type == 7 || this.type == 10){ //红蓝和护网/综合演练
				if(_this.allOptionalVms.length > 0){
					let vmslists =  this.allOptionalVms.map(vm => {
						let showName = vm.name+'('+vm.networkName+')'
						return {
							key:vm.id,
							label:showName,
							name:vm.name,
							disabled: this.rangeId && this.rangeId !== vm.rangeId
						}
					})
					return vmslists
				}
			}else{
				if(_this.allOptionalVms.length > 0 && _this.subnetList.length > 0){
					let selnw;
					let vmlist = this.allOptionalVms;
					let disabled;
          			let vmslists =   vmlist.map(vm => {
						let showName = vm.name+'('+vm.networkName+')'
						return {
							key:vm.id,
							label:showName,
							name:vm.name,
							disabled: this.rangeId && this.rangeId !== vm.rangeId
						}
					})
					return vmslists
				}else{
					return []
				}
			}
		},
		disabledAutoAllot:function(){
			this.autoConfigTip = '';
			if(this.allVms.length == 0){
				this.autoConfigTip = ''
			}else if(this.accessGroupList.length == 0){
				this.autoConfigTip = `[${this.type === 10 ? '角色':'团队'}没有配置，无法自动分配]`
			}else if(this.allProjectGroupMember.length == 0){
				this.autoConfigTip = `[${this.type === 10 ? '角色':'团队'}没有分配人员，无法自动分配]`
			}
			return !(this.allVms.length > 0 && this.accessGroupList.length > 0 && this.allProjectGroupMember.length > 0)
		}
	},
	mounted(){
		this.getProjectInfo();
    	this.getAccessGroupList();
		this.getPartyList().then(data => {
			this.getProjectGroupMember();
		});
    	this.getAllProjectGroupMember(); //自动分配使用
		this.getAllVms();//自动分配使用
		if(this.type == 7){
			this.userColumns.splice(4,1);
		}
		if(this.hlConfig == 2){
			this.userColumns.splice(4,1);
		}
		if(this.type == 10){ //应急防御演练势力方和已分配网络都不要
			this.userColumns.splice(3,2);
		}
	},
	methods:{
		getAccessGroupList(){
			if(!this.testId){
				return;
			}
			let params = {
				pageIndex:1,
				pageSize:2147483647,
				testId:this.testId
			};
			getaccessgrouplist(params).then(data => {
				if(data.code == 1){
					if (this.type == '2') {
						let items = data.data.items || []
						this.accessGroupList = items
						// 夺旗赛过滤掉spare1组
						this.teamOptions = items.filter(item => !item.spare)
					} else {
						this.accessGroupList = data.data.items || []
						this.teamOptions = data.data.items || []
					}
					if (this.type === 5) {
						this.teamOptions = this.teamOptions.filter(item => item.name !== '目标方管理员组')
					}
				}else if(data.code == -2) {
					this.accessGroupList = [];
				}else{
					this.$Message.warning(data.message);
				}
			})
		},
		getHostDetail(id){
			let params = {
				id:id
			}
			return new Promise((resolve,reject) => {
				queryVmWithParty(this.projectId,params).then(data => {
				 	if(data.code == 1 && data.data.list.length > 0){
				 		let vm = data.data.list[0];
				 		let party = this.partyList.filter(party => party.id == vm.party)[0];
				 		if(party){
				 			party.partyColor = `rgba(${party.red},${party.green},${party.blue},${party.alpha})`;
				 		}
				 		vm.party = party;
				 		resolve(vm)
				 	}else{
				 		resolve()
				 	}
				})
			}).catch(error => {
				resolve()
			})
		},
		getPartyList(){
			return new Promise((resolve,reject) => {
				if(!this.projectId){
					return;
				}
				let params = {projectId:this.projectId}
				getpartylist(params).then(data => {
					if(data.code == 1){
						this.partyList = data.attribute.dataList;
						resolve(data.attribute.dataList);
					}else if(data.code == -2) {
						this.partyList = [];
						resolve([]);
					}else{
						this.$Message.warning(data.message);
						resolve([]);
					}
				}).catch(error => {
					resolve([]);
				})
			})
		},
		handleReset (name) {
            //this.$refs['groupFormValidate'].resetFields();
        },
        getAllProjectGroupMember(){
			if(!this.testId){
				return;
			}
			let params = {
				testId:this.$route.query.id,
				pageIndex:1,
				pageSize:2147483647
			}
			getuserinstance(params).then(data => {
				if(data.code == 1){
					this.allProjectGroupMember = data.data.items.filter(item => item.inviterName != '内部服务用户');
					this.getMemberSuccess = true;
				}else if(data.code == -2){

				}else{
					this.$Message.warning(data.message);
				}
			})
	    },
		getProjectGroupMember(){
			if(!this.testId){
				return;
			}
			this.selectUserList = [];
			getUserInstanceExclude(this.queryGroupMemberInfo).then(data => {
				if(data.code == 1){
					let projectGroupMemberList = data.data.data
					this.groupMemberTotal = data.data.total;
					let promiseArr = projectGroupMemberList.map(async group => {
						if(group.deviceList.length > 0){
							let vmInfo = await this.getHostDetail(group.deviceList[0].deviceId) || {};
							let networkName = vmInfo.networkName;
							group.networkName = networkName;
							group.party = vmInfo.party;
							return group;
						}else{
							group.networkName = '';
							return group;
						}
					});
          setTimeout(()=>{
            Promise.all(promiseArr).then(data => {
              this.projectGroupMemberList = data;
            })
          },500)

				}else if(data.code == -2){
					this.projectGroupMemberList = [];
				}else{
					this.$Message.warning(data.message);
				}
			})
	    },
	    changeSize(size){
			this.queryGroupMemberInfo.pageSize = size;
			this.getProjectGroupMember();
		},
		changePage(page){
			this.queryGroupMemberInfo.pageIndex = page;
			this.getProjectGroupMember();
		},
		accessVm(){
			this.accessVmModal.show = true;
		},
		rowClassName (row, index) {
            if (row._isExpanded) {
                return 'demo-table-info-row';
            }
            return '';
        },
		render1(vm){
//			return '<span title="'+ vm.label +'">' + vm.label +  '<span style="float:right">'+ vm.vmRecord + '</span></span>'
			//return '<span title="'+ vm.label +'">'+ vm.label + '</span>'
			return vm.label;
		},
		async getOptionalVms(network){
			let params = {
				page:1,
				pageSize:100000,
				sortBy:'name',
				order:'asc',
				findPorts:true
			}
			if(this.type != 7&&(this.type==0&&this.hlConfig!=2)){ //不是综合演练和 对抗演练的2模式
				params.party = this.selectUser.partyId;
			}
			if(this.isClientType(this.type)){
				params.vmType =  "CLIENT"
			}
			if(this.networkId){
				if(this.networkId == 'all'){

				}else{
//					params.networkId = this.networkId;
				}
			}
			await queryVmWithParty(this.projectId,params).then(data => {
				if(data.code == 1){
					if([1, 2, 8, 9].includes(this.type)){
						this.allOptionalVms = data.data.list.filter(vm => vm.address[0] && vm.address[0].ips[0] && vm.address[0].ips[0].ipAddress.indexOf('192.168.20') != -1);
					}else{
						this.allOptionalVms = data.data.list;
					}
				}
			})
			if (this.type === 9) { // 运维赛在获取接入机器时，还要额外获取安全运维赛题的虚拟机作为接入机器
				let params = {
					page:1,
					pageSize:100000,
					sortBy:'name',
					order:'asc',
					findPorts:true,
					vmType: 'SERVER',
					party: this.selectUser.partyId
				}
				Promise.all([getTargetTeamList_new({
					pageIndex:1,
					pageSize:10,
					sceneId:this.$route.query.id,
					projectId:this.$route.query.prjid
				}), queryVmWithParty(this.projectId,params)]).then(([res1, res2]) => {
					let opQuestionNames = []
					if (res1.code !== 1) {
						this.$Message.warning(res1.message)
						return
					}
					res1.data.items.forEach(item => {
						if (item.category === '安全运维') {
							opQuestionNames.push(item.name)
						}
					})
					if (res2.code !== 1) {
						this.$Message.warning(res2.message)
						return
					}
					let vms = []
					if (res2.code !== 1) {
						this.$Message.warning(res1.message)
						return
					}
					vms = res2.data.list.filter(item => opQuestionNames.includes(item.name));
					this.allOptionalVms = this.allOptionalVms.concat(vms)
				})
			}
		},
		getAllVms(){
			let params = {
				page:1,
				pageSize:100000,
				sortBy:'name',
				order:'asc',
				findPorts:true
			}
			if(this.isClientType(this.type)){
				params.vmType =  "CLIENT"
			}
			queryVmWithParty(this.projectId,params).then(data => {
				if(data.code == 1){
					if([1, 2, 8, 9].includes(this.type)){
						this.allVms = data.data.list.filter(vm => vm.address[0] && vm.address[0].ips[0].ipAddress.indexOf('192.168.20') != -1);
					}else{
						this.allVms = data.data.list;
					}
				}
			})
			if (this.type === 9) { // 运维赛在获取接入机器时，还要额外获取安全运维赛题的虚拟机作为接入机器
				let params = {
					page:1,
					pageSize:100000,
					sortBy:'name',
					order:'asc',
					findPorts:true,
					vmType: 'SERVER',
					party: this.selectUser.partyId
				}
				Promise.all([getTargetTeamList_new({
					pageIndex:1,
					pageSize:10,
					sceneId:this.$route.query.id,
					projectId:this.$route.query.prjid
				}), queryVmWithParty(this.projectId,params)]).then(([res1, res2]) => {
					let opQuestionNames = []
					if (res1.code !== 1) {
						this.$Message.warning(res1.message)
						return
					}
					res1.data.items.forEach(item => {
						if (item.category === '安全运维') {
							opQuestionNames.push(item.name)
						}
					})
					if (res2.code !== 1) {
						this.$Message.warning(res2.message)
						return
					}
					let vms = []
					if (res2.code !== 1) {
						this.$Message.warning(res1.message)
						return
					}
					vms = res2.data.list.filter(item => opQuestionNames.includes(item.name));
					this.allVms = this.allVms.concat(vms)
				})
			}
		},
		isClientType(type) {
			return [1, 2, 4, 5, 8, 9].includes(type)
		},
		handleChangeVm(targetKeys, direction, moveKeys){
			this.selectVms = targetKeys;
			this.deviceToUser();
		},
		handleChangeSelectVm(sourceSelectedKeys, targetSelectedKeys){
			this.curSelectVms = sourceSelectedKeys;
		},
		removeDevice(e,deviceId){
			let delDeviceId = [deviceId]; //待删除机器
			let curUserDeviceIds = this.selectUser.deviceList.map(device => device.deviceId); //当前接入机器
			let newUserDevices = curUserDeviceIds.filter(id => !delDeviceId.includes(id));
            this.selectVms = newUserDevices;
			this.deviceToUser('tagRemove');
        },
        clearDevices(){
        	this.handleChangeVm([]);
        },
		deviceToUser(type){
			let devices = [];
			if(type == 'tagRemove'){
				devices = this.selectVms.map(vmId => {
					let vm = this.selectUser.deviceList.filter(vm => vm.deviceId == vmId)[0];
					return {
						"deviceId": vm.deviceId,
			      		"deviceName": vm.deviceName,
			      		"deviceType": "VM",
			      		"enableRecordScreen": this.record,
			      		"enabled": this.access
					}
				});
			}else{
				devices = this.selectVms.map(vmId => {
					let vm = this.optionalVms.filter(vm => vm.key == vmId)[0];
					return {
						"deviceId": vm.key,
			      		"deviceName": vm.label,
			      		"deviceType": "VM",
			      		"enableRecordScreen": this.record,
			      		"enabled": this.access
					}
				});
			}
			let params = {
			    "accessGroupId": this.selectUser.accessGroupId,
			    "devices": devices,
			    "testId": this.testId,
			    "userId": this.selectUser.userId
			}
			setuservmrelation(params).then(data => {
				if(data.code == 1){
					//this.accessVmModal.show = false;
					this.getProjectGroupMember();
					this.selectUser.deviceList = devices;
				}else{
					//this.cancelLoading('accessVmLoading');
					this.$Message.warning(data.message);
				}
			})
		},
		cancelLoading(name){
	    	this[name].loading = false;
	      	setTimeout(() => {
	      		this[name].loading = true;
	      	})
	    },
		filterMethod (data, query) {
			return data.label.indexOf(query.trim()) > -1;
        },
        getProjectInfo(){
			getstatusbyprjid(this.$route.query.prjid).then(data => {
				if(data.code == 1){
					this.projectInfo = data.attribute;
					this.getProjectSubnet();
				}
			})
		},
        getProjectSubnet(){
	    	queryNetworkList(this.$route.query.prjid,this.projectInfo.network.id).then(data => {
	    		if(data.code == 1){
	    			let subnetList = [];
	    			data.attribute.editorStage.childs.forEach(item => {
	    				subnetList = subnetList.concat(item.childs);
	    			})
	    			this.subnetList = subnetList.filter(subnet => subnet.dataType == 'NW');
//	    			this.networkId = subnetList[0].id;
					if(this.subnetList.length > 0){
//						this.network = {
//		    				value:this.subnetList[0].id,
//		    				label:this.subnetList[0].name
//		    			}
					}
	    			this.getOptionalVms();
	    		}
	    	})
	    },
		// 随机分配，取随机的一台win机器、一台kali机器
		randomAllocation(group = {}) {
			let winVms = [], kaliVms = [], vmList = group.vmList || []
			// vmList.forEach(item => {
			// 	let name = item.name || ''
			// 	name.endsWith('kali') ? kaliVms.push(item) : (name.endsWith('win') ? winVms.push(item) : '')
			// })
			vmList.forEach(item => {
				let name = item.name || ''
				item.sysType === 'windows' ? kaliVms.push(item) : (item.sysType === 'linux' ? winVms.push(item) : '')
			})
			return [winVms[Math.floor((Math.random()*winVms.length))], kaliVms[Math.floor((Math.random()*kaliVms.length))]]
		},
	    async dealAutoAllotData(){
			this.disabledAutoAllot1 = true;
			//bug21874后改为后端分配
			// //获取分配了人员的组
			// let accessGroupList = [...new Set(this.allProjectGroupMember.map(member => member.accessGroupId))].map(groupId => {
			// 	let group = this.accessGroupList.filter(group => group.id == groupId)[0]
			// 	return group;
			// });
			// accessGroupList = accessGroupList.filter(item => item != undefined)
			// accessGroupList.sort((a,b) => {
			// 	return a.userList.length - b.userList.length
			// })
			// //子网及机器
			// let subnetList = [].concat(this.subnetList);
			// let allOptionalVms = JSON.parse(JSON.stringify(this.allVms));
			// subnetList.forEach(subnet => {
			// 	subnet.deviceList = allOptionalVms.filter(vm => subnet.id == vm.networkId)
			// })
			// subnetList.sort((a,b) => {
			// 	return a.deviceList.length - b.deviceList.length
			// })
			// //给组分配子网和机器
			// accessGroupList.forEach((group,index) => {
			// 	if([1, 2, 4, 5, 8, 9].includes(this.type)){ //护网,夺旗,渗透攻防
			// 		let vms = allOptionalVms.filter(vm => {
			// 			if(!vm.party){
			// 			}
			// 			return group.partyId == (vm.party && vm.party.toString())
			// 		})
			// 		vms.forEach(vm => {
			// 			vm.used = false;
			// 			vm.name = vm.name
			// 		})
			// 		group.vmList = vms;
			// 	}else{
			// 		if(subnetList.length > index){
			// 			let subnet = subnetList[index];
			// 			//机器按镜像分组
			// 			//let imageVm = {};
			// 			let vms = subnet.deviceList;
			// 			vms.forEach(vm => {
			// 				vm.used = false;
			// 				vm.name = vm.name
			// 			})
			// 			group.subnet = subnet;
			// 			group.vmList = vms;
			// 		}
			// 	}
			// })
			// let allProjectGroupMember = JSON.parse(JSON.stringify(this.allProjectGroupMember));
			// // 给人员分配机器
			// allProjectGroupMember.forEach(member => {
			// 	let group = accessGroupList.filter(group => group.id == member.accessGroupId)[0]
			// 	let groupDevices = group.vmList;
			// 	/**
			// 	 * 护网演练，每个用户对应两个接入机器，接入机器的名称为“势力方名-用户名-kali”和“势力方名-用户名-win”
			// 	 */
			// 	if (this.type === 5) {
			// 		// 过滤出以势力方名-昵称开头的接入机器，没有匹配的用户随机分配同一势力方内的接入机器
			// 		groupDevices = groupDevices.filter(item => (item.name || '').startsWith(`${group.name}-${member.userName}-`))
			// 		groupDevices.length === 0 ? groupDevices = this.randomAllocation(group) : ''
			// 	}
			// 	// 过滤掉 不是这个昵称下的机器 21858
			// 	// user.user.username + '(' + user.user.nickname + ')';
			// 	let userName = member.userName||''
			// 	// let gDevices = groupDevices.filter(item=>{
			// 	// return item.address[0].deviceName.includes(userName)
			// 	// })
			// 	member.devices = groupDevices;
			// })
			// let data = allProjectGroupMember.map(member => {
			// 	return {
			// 		"accessGroupId": member.accessGroupId,
			// 		"devices": member.devices ? member.devices.map(device => {
			// 			return {
			// 				"deviceId": device.id,
			// 				"deviceName": device.name + '('+device.networkName+')',
			// 				"deviceType": "VM",
			// 				"enableRecordScreen": true,
			// 				"enabled": true
			// 			}
			// 		}) : [],
			// 		"testId": this.testId,
			// 		"userId": member.userId
			// 	}
			// })
			// let prr = data.map(async params => {
			// 	await setuservmrelation(params).then(data => {
			// 		if(data.code == 1){
			// 		}else{
			// 			this.$Message.warning(data.message);
			// 		}
			// 	})
			// })
			// Promise.all(prr).then(data => {
			autoConfigAccessVm(this.testId).then(data => {
				this.$Message.info('接入成功');
				this.disabledAutoAllot1 = false;
				// 分配成功后清空搜索条件，回退到首页
				this.queryGroupMemberInfo.pageIndex = 1
				this.queryGroupMemberInfo.accessGroupId = undefined
				this.getProjectGroupMember();
				// 视情况需要同步分配题目
				if ([1, 4, 8, 9].includes(this.type)) { // 渗透赛、攻防赛、攻防赛Plus，查看是否有题目，有的话同步分配题目
					getTargetTeamList_new({
						pageIndex:1,
						pageSize:10,
						sceneId:this.$route.query.id,
						projectId:this.$route.query.prjid
					}).then(({ code, message, data }) => {
						if(code == 1){
							if (data.total != 0) { // 有题目，分配题目
								autoAllotTopoTarget(this.$route.query.id).then(data => {
									if(data.code != 1){
										this.$Message.warning(data.message);
									}
								})
							}
						}else{
							this.$Message.warning(message)
						}
					})
				}
				if (this.type == 2) { // 夺旗赛
					queryCtfTarget(this.$route.query.id, {
						pageIndex:1,
						pageSize:10,
						sceneId:this.$route.query.id,
						projectId:this.$route.query.prjid
					}).then(({ code, message, data }) => {
						if(code == 1){
							if (data.total != 0) { // 有题目，分配题目
								// 需要先撤销分配，在重新分配，否则可能存在提示重复分配的问题
								ctfTargetAllot({ // 撤销
									"projectId": this.$route.query.prjid,
									"sceneId": this.$route.query.id,
									"status": 0
								}).then(() => {
									ctfTargetAllot({ // 无论撤销是否成功，开始重新分配
										"projectId": this.$route.query.prjid,
										"sceneId": this.$route.query.id,
										"status": 1
									}).then(data => {
										if(data.code != 1){
											this.$Message.warning(data.message);
										}
									})
								})
							}
						}else{
							this.$Message.warning(message)
						}
					})
				}
			}).catch((error) => {
				this.disabledAutoAllot1 = false;
			})
		}
	}
}
</script>

<style>
    #access .demo-table-info-row>td{
		background:lightblue
	}
	#access .ivu-table-overflowX{
		overflow-x: hidden;
	}
</style>
